{% extends "siteSetting/set_base.html" %}
{% block title %}车辆属性{% endblock %}
{% block head %}
{{ super() }}
<link rel="stylesheet" href="{{ url_for('static', filename='css/uikit.min.css') }}">
<link rel="stylesheet" href="{{ url_for('static', filename='css/sortable.min.css') }}">

{% if color_values %}  {# 只有颜色用到下面的#}
<style>
    .uk-modal {
        z-index: 1000;
    }
</style>
{% endif %}

{% endblock %}


{% macro render_modal(name) %}
<div id="modal-{{ name }}" class="uk-modal myModal" aria-hidden="true" style="display: none; overflow-y: scroll;">
    <div class="uk-modal-dialog">
        <button type="button" class="uk-modal-close uk-close"></button>
        <div class="uk-modal-header">
            <h3>新增-{{ name_dict[name] }}</h3>
        </div>
  		<div class="uk-modal-body">
            <form action="/setting/carAttribute/new_item/{{ name }}" method="post" id="id-form-new">
                <div class="form-group">
                <label for="{{ name }}">{{ name_dict[name] }}</label>
				{% if name == 'price' or name == 'car_age' or name == 'mileage' or name == 'exhaust' %}
				<div class=" form-inline">
                	<input class="form-control" id="{{ name }}" name="{{ name }}" required="" type="text">
                	<input type="text" name="range" class="form-control" required="" placeholder="对应范围"
						   style="width: 120px;">
                	——
                	<input type="text" name="range" class="form-control" placeholder="对应范围"
						   style="width: 120px;">

                </div>
                {% elif name == 'color' %}

                    <div class="form-inline">
                    <input class="color-button jscolor form-control" style="width: 80px;" value="" name='color_value' id="new_color_value">
                          &nbsp;&nbsp;&nbsp;
                    </input>
                    <input class="form-control" id="{{ name }}" name="{{ name }}" required="" type="text">
                    </div>
				{% else %}
                <input class="form-control" id="{{ name }}" name="{{ name }}" required="" type="text">
                {% endif %}
                </div>
                <button class="btn btn-primary">保存</button>
            </form>
  		</div>
    </div>
</div>
{% endmacro %}

{# xxx : {xxx:[{"sort":1, 'id':'xx', 'value':xx}]  或 {xxx: []}  #}
{# l : [{"sort":1, 'id':'xx', 'value':xx}]  或 []  #}

{% block page_content %}
<h1 class="page-header">车辆属性</h1>
{% set name = d.keys()[0] %}
{% set l = d[name] %}

<h2>
编辑-{{ name_dict[name] }}
</h2>
{{ render_modal(name) }}
<form action="/setting/carAttribute/update/{{ name }}" method="post" class="uk-form"  data-name="{{ name }}" id="id-data-name">
<button class="save btn btn-primary" data-url="/setting/carAttribute/update" id="id-button-save">保存</button>
<button class="delete btn btn-danger" type="button">删除</button>
<button class="new btn btn-info" data-uk-modal="{target:'#modal-{{ name }}'}" type="button">新增</button>

{% if l %}
{% if name == 'price' or name == 'car_age' or name == 'mileage' or name == 'exhaust' %}  {# 四个带有范围的字段 #}
<ul class="my-sortable uk-sortable uk-grid uk-grid-small uk-grid-width-1-3" data-uk-sortable="" style="">
	{% for item in l %}
    {% set id = item.get('id') %}
    {% set name1 = name + id %}
    {% set min = rel.get(name1)[0] %}
	{% set max = rel.get(name1)[1] %}
	<li class="uk-grid-margin" style="">
	    <div class="uk-panel uk-panel-hover">
	        <!-- <input type="checkbox" name="delete" class="input-delete" value="{{ item.get('id') }}(⊙o⊙){{ item.get('value').encode('utf-8').decode('utf-8') }}"> -->
            <input type="checkbox" name="delete" class="input-delete" value="{{ item['id'] }}">

	        <span><b class="sort-id">{{ item.get('sort') }}</b></span> |
	        <span class='{{ name }}-text' style="display: inline;">

	            <input name="{{ name }}" value="{{ item.get('value').encode('utf-8').decode('utf-8') }}" style="width: 90px;">
	            <span class="form-inline">
				<input type="text" name="range" required="" style="width: 50px;" value="{{ min }}">
	        	—
	        	<input type="text" name="range" style="width: 50px;" value="{{ max }}">
                <input type="hidden" name="id" value="{{ id }}">
	            </span>
	        </span>
	    </div>
	</li>
	{% endfor %}

{% elif name == 'color' %}
<ul class="my-sortable uk-sortable uk-grid uk-grid-small uk-grid-width-1-4" data-uk-sortable="" style="">
	{% for item in l %}
    {% set id = item.get('id') %}
    {% set sort = item.get('sort') %}
    {% set color_name = item.get('value') %}
    {% set color_value = color_values.get(id) %}
	<li class="uk-grid-margin" style="">
	    <div class="uk-panel uk-panel-hover">
	        <!-- <input type="checkbox" name="delete" class="input-delete" value="{{ id }}(⊙o⊙){{ color_name.encode('utf-8').decode('utf-8') }}"> -->
            <input type="checkbox" name="delete" class="input-delete" value="{{ item['id'] }}">
	        <span><b class="sort-id">{{ sort }}</b></span> |
	        <span class='{{ name }}-text' style="display: inline;">
                <input class="color-input jscolor form-control" style="width: 80px;" name="color_value" value="{{ color_value }}">
                      &nbsp;&nbsp;&nbsp;
                </input>
                <input type="hidden" name="id" value="{{ id }}">
	            <input name="{{ name }}" value="{{ color_name.encode('utf-8').decode('utf-8') }}" >
	        </span>
	    </div>
	</li>
	{% endfor %}

{% else %}
{# l : [{"sort":1, 'id':'xx', 'value':xx}]  或 []  #}
<ul class="my-sortable uk-sortable uk-grid uk-grid-small uk-grid-width-1-4" data-uk-sortable="" style="">
	{% for item in l %}
    {% set f_name = item['value'] %}
	<li class="uk-grid-margin" style="">
	    <div class="uk-panel uk-panel-hover">
	        <!-- <input type="checkbox" name="delete" class="input-delete" value="{{ item['id'] }}(⊙o⊙){{ f_name.encode('utf-8').decode('utf-8') }}"> -->
            <input type="checkbox" name="delete" class="input-delete" value="{{ item['id'] }}">
	        <span><b class="sort-id">{{ item['sort'] }}</b></span> |
	        <span class='{{ name }}-text' style="display: inline;">
            <input name="id" type="hidden" value="{{ item['id'] }}">
	        <input name="{{ name }}" value="{{ f_name.encode('utf-8').decode('utf-8') }}">
	        </span>
	    </div>
	</li>
	{% endfor %}

{% endif %}

</ul>
{% endif %}
</form>
{% endblock %}

{% block scripts  %}
{{ super() }}

<script src="{{ url_for('static', filename='js/jquery.min.js') }}"></script>
<script src="{{ url_for('static', filename='js/jscolor.min.js') }}"></script>
<script src="{{ url_for('static', filename='js/uikit.min.js') }}"></script>
<script src="{{ url_for('static', filename='js/sortable.min.js') }}"></script>
<script>
    var ajaxPost = function (url, method, form, success, error) {
        var request = {
            url: url,
            type: method,
            contentType: 'application/json',
            success: function (r) {
                success(r);
            },
            error: function (err) {
                r = {
                    success: false,
                    data: err
                };
                error(r);
            }
        };
        if (method === 'post') {
            var data = JSON.stringify(form);
            request.data = data;
        }
        $.ajax(request);
    };
    var success = function (r) {
        alert(r.message);
    };
    var error = function (err) {
            
    };   
    var deleteForm = function () {
        var l = [];
        $.each($(".input-delete"), function () {
            if ($(this).is(':checked')) {
                var value = $(this).val();
                l.push(value);
            }
        });
        if (l.length === 0) {
            alert('你还没有选中条目');
            return 0;
        }        
        return l;        
    }

    var sendDelete = function (l) {

        var name = $("#id-data-name").data('name');

        var form = {};
        var url = '/setting/carAttribute/delete';
        var method = 'post';
        form[name] = l;
        console.log('delete form', form);
        var success = function (r) {
        	UIkit.modal.confirm(r.message, function(){
                   location.reload();
            });
        }
        ajaxPost(url, method, form, success, error);

        // var input_delete = s.closest('div').find("input.input-delete");
        // var blocks = s.closest('div').find(".div-sort-block");
        // var p = $(blocks[0]).data('name');
        // var delete_dict = {};
        // for (var i = 0; i < input_delete.length; i++) {
        //     var input_id = $(input_delete[i]).closest('div').find('input.input-id');
        //     var brand_text = $(input_delete[i]).closest('div').find('div.brand-text');
        //     if ($(input_delete[i]).is(':checked')) {
        //         var id = $(input_id).val();
        //         delete_dict[id] = brand_text.html();
        //     }
        // };
        // if (JSON.stringify(delete_dict) == '{}') {
        //     alert('no selected item');
        //     return 0
        // }
        // var url = '/setting/carAttribute/delete';
        // var method = 'post';
        // var form = {};   // {'brand': {'1': 'davs', '2': 'mazida'}}

        // form[p] = delete_dict;
        // console.log('delete form', form);
        // ajaxPost(url, method, form, success, error);

    };

    
    var bindActions = function () {
        $("button.delete").on('click', function () {
            l = deleteForm();
            if (l) {
                UIkit.modal.confirm("确定删除吗?", function(){
                    sendDelete(l);  // 点击OK确认后开始执行

                });
            }
        });
    };
    
    var fillSortId = function (event) {  {# 拖动结束后把序号按从小到大改写 #}
        if (event === '') {
            var s = $("ul.my-sortable .sort-id");
        } else {
            var self = event.target;
            var s = $(self).closest('ul').find('.sort-id');
        }
        $.each(s, function (e) {
            $(this).html(e + 1);
        });
    };
    
    $(".my-sortable").on('stop.uk.sortable', function(event) {
            fillSortId(event);
        });

    bindActions();

    fillSortId('');

</script>

{% if color_values %}  {# 只有颜色用到下面的JS#}
<script>
    var check_repeat = function (new_color_value) {
        var list = [];
        $.each($(".color-input"), function(e) {
            var v = $(this).val();
            list.push(v);
        });
        if (new_color_value) {
            list.push(new_color_value);
        };
        var nary=list.sort(); 
        console.log('sort', nary);
        for(var i=0;i<list.length;i++){
            if (nary[i]==nary[i+1]){
                return false;
            }
        };
        return true
    };

    $('#id-data-name').submit( function( e ) {
        e.preventDefault();
        var no_repeat = check_repeat('');
        console.log(no_repeat);
        if (no_repeat) {
            var url = $(this).attr('action');
            $.ajax( {
                url: url,
                type: 'POST',
                data: new FormData( this ),
                processData: false,
                contentType: false,
                success: function(r) {
                    window.location.reload();
                }
            }
            );
        } else {
            alert('不能填入颜色相同的值, 保存失败');
            return false;
        }
    });

    $('#id-form-new').submit( function( e ) {
        e.preventDefault();
        var new_color_value = $("#new_color_value").val();
        var no_repeat = check_repeat(new_color_value);
        console.log('new',no_repeat);
        if (no_repeat) {
            var url = $(this).attr('action');
            $.ajax( {
                url: url,
                type: 'POST',
                data: new FormData( this ),
                processData: false,
                contentType: false,
                success: function(r) {
                    window.location.href = '/setting/carAttribute/edit/color'
                }
            }
            );
        } else {
            alert('不能填入颜色相同的值, 保存失败');
            return false;
        }
    });
        

</script>
{% endif %}


<script>
    nav = document.getElementById("nav_car_attr");
    nav.setAttribute("class", "active");
</script>
{% endblock %}
